/**
 * crawler
 *
 * outlook@China software studio
 * Copyright (c) 2008-2010. All Rights Reserved.
 * http://www.outlook.com
 */

package org.outlook.crawler.util;

import java.util.HashMap;
import java.util.Map;

import org.outlook.crawler.client.exception.EvaluateException;
import org.outlook.crawler.client.pojo.Status;

/**
 * function:
 * @author Watson email: watson.wu@hotmail.com
 * @date 2011
 */
public class CrawlTaskMonitor {

	public static Map<String, Status> pageStatus = new HashMap<String, Status>();
	
	private static int success_num = 0; 
	
	public static float getSuccessPrecent() {
		return (float)success_num/pageStatus.size();
	}
	
	public static boolean addPage(String url) throws EvaluateException {
		synchronized (pageStatus) {
			if(isURlProccessed(url))
				return false;
			else
				pageStatus.put(url, Status.PEND);
		}
		return true;
	}
	
	public static void updatePage(String url, int httpStatus) throws EvaluateException {
		if(!isURlProccessed(url))
			throw new EvaluateException("url not exist in task");
		final Status status = getStatus(httpStatus);
		synchronized (pageStatus) {
			pageStatus.put(url, status);
		}
		if(status.equals(Status.OK))
			success_num++;
			
	}
	
	public static boolean isURlProccessed(String url) {
		return pageStatus.get(url)!=null;
	}
	
	public static boolean isExistURlProccessing(String url) {
		return pageStatus.get(url).equals(Status.PEND);
	}
	
	public static boolean isURlProccessedOk(String url) {
		return pageStatus.get(url).equals(Status.OK);
	}
	
	public static boolean isURlProccessedError(String url) {
		return pageStatus.get(url).equals(Status.ERROR);
	}
	
	public static boolean isURlProccessedMissing(String url) {
		return pageStatus.get(url).equals(Status.MISS);
	}
	
	public static boolean isURlProccessedInvalid(String url) {
		return pageStatus.get(url).equals(Status.INVALID);
	}

	private static Status getStatus(int httpStatus) {
		switch (httpStatus/100) {
		case 1:
			return Status.INVALID;
		case 2:
			return Status.OK;
		case 3:
			return Status.MISS;
		case 4 :
		case 5 :
		return Status.ERROR;
		default:
			return Status.PEND;
		}
	}

}
